﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Furion.Schedule;

namespace Abc.Core.EventBus;

/// <summary>
/// 清理正在处理的job
/// </summary>
[JobDetail("job_EventBusClearProcessingDataJob", concurrent: false, "清理正在处理的job")]
//文档：26.1.5.6 作业触发器特性及自定义
[PeriodSeconds(5, TriggerId = "trigger_EventBusClearProcessingDataJob")]
public class EventBusClearProcessingDataJob : IJob
{

    public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
    {
        var _logger = AppEx.GetSeriLogger(logFloderName: $"EventBus\\ClearProcessingDataJob\\");
        var option = AppEx.GetConfig<EventBusOptions>();
        //判断是否开启了事件总线
        if (option.IsEnableEventBus == false)
        {
            await Task.CompletedTask;
            return;
        }
        try
        {
            //调用移除过期数据方法
            // EventBusCenter.Instance.RemoveExpirationData();
            foreach (var key in EventBusHelper.Instance.ProcessingEventSubscribes.Keys.ToList())
            {
                //判断处理中的集合是否还存在 此key
                if (!EventBusHelper.Instance.ProcessingEventSubscribes.ContainsKey(key)) continue;
                var processing = EventBusHelper.Instance.ProcessingEventSubscribes[key];

                //判断是否超出了最大处理时间，防止死数据产生
                if (processing.MaxProcessingTime < DateTimeOffset.Now)
                {
                    //已过期，从处理中的数据集合中 移除
                    EventBusHelper.Instance.ProcessingEventSubscribes.TryRemove(key, out _);
                    continue;
                }

                //跳过未处理的数据
                if (processing.ExpirationTime == null) continue;
                //判断是否过期了
                if (processing.ExpirationTime < DateTimeOffset.Now)
                {
                    //已过期，从处理中的数据集合中 移除
                    EventBusHelper.Instance.ProcessingEventSubscribes.TryRemove(key, out _);
                }
            }
        }
        catch (Exception ex)
        {
            _logger.Error(ex.ToStringEx());
        }
        finally
        {

        }

        await Task.CompletedTask;
    }
}
